package com.job.Interceptor;

import com.job.common.Constant;
import com.job.common.required.HrRequired;
import com.job.pojo.LoginUser;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class HrInterceptor implements HandlerInterceptor, Constant {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            HrRequired hrRequired = method.getAnnotation(HrRequired.class);
            LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            Integer userType = loginUser.getUser().getUserType();
            if (hrRequired != null &&  userType != HR) {
                response.sendRedirect(request.getContextPath() + "/index");
                return false;
            }
        }
        return true;
    }
}
